import {getDepartmentsAPI, getSimpleEmployeesAPI, addDepartmentsAPI, deleteDepartmentAPI, findDepartmentDetailAPI, updateDepartmentDetailAPI} from '@/api/departmentsApi'
import {transitionToTreeData} from '@/utils'

const actions = {
  /* 发送请求获取部门列表的action */
  async fetchDepartments({commit}) {
    const {data: {depts}} = await getDepartmentsAPI()
    commit('updateDepartments', depts)
  },
  /* 发送请求获取部门负责人(所有员工)的action */
  async fetchSimpleEmployees({commit}) {
    const {data: simpleEmployees} = await getSimpleEmployeesAPI()
    commit('updateSimpleEmployees', simpleEmployees)
  },
  /* 发送请求添加一个部门的action */
  async addDepartments({commit}, department) {
    const {message} = await addDepartmentsAPI(department)
    return message
  },
  /* 发送请求删除一个部门的action */
  async deleteDepartment({commit}, id) {
    const {message} = await deleteDepartmentAPI(id)
    commit('deleteDepartment', id)
    return message
  },
  /* 发送请求查找一个部门的action */
  async findDepartmentDetail({commit}, id) {
    const {data: department} = await findDepartmentDetailAPI(id)
    return department
  },
  /* 发送请求更新一个部门的action */
  async updateDepartmentDetail({commit}, department) {
    const {message} = await updateDepartmentDetailAPI(department)
    return message
  }

}
const mutations = {
  /* 更新部门列表的mutation */
  updateDepartments(state, departments) {
    state.departmentList = departments
  },
  /* 更新部门负责人的mutation */
  updateSimpleEmployees(state, simpleEmployees) {
    state.simpleEmployees = simpleEmployees
  },
  /* 删除部门的mutation */
  deleteDepartment(state, id) {
    state.departmentList = state.departmentList.filter(item => item.id !== id)
  }
}
const state = () => {
  return {
    /* 部门列表(平铺) */
    departmentList: [],
    /* 部门的负责人 */
    simpleEmployees: [],

  }
}
const getters = {
  /* 转换后的树形部门列表(使用transitionToTreeData函数将平铺的数组转为树形数组) */
  treeDepartments: state => transitionToTreeData(state.departmentList),
  /* 用于给组件进行校验的部门列表(只有id、pid、name、code字段) */
  simpleDepartments: state => state.departmentList.filter(item => item.pid !== '-1').map(({id, pid, name, code}) => ({id, pid, name, code}))
}

export default {
  actions,
  mutations,
  state,
  getters,
  namespaced: true
}
